package com.bilibilifans.data;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

/**
 * @author 司啸飞
 * @create 2021-05-12 17:33
 */
public class MyCode {

    /**
     * 获取API中的数据 返回一个字符串数组，包含以 ' , ' 分割
     * @param sURL
     * @return
     * @throws Exception
     */
    public static HashMap<String, String> getCode(String sURL, String[] GET_DATA) throws Exception {
        //读取目的网页URL地址，获取网页源码
        URL url = new URL(sURL);
        HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
        InputStream is = httpUrl.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
        StringBuilder sb = new StringBuilder();

        String line;
        while ((line = br.readLine()) != null) {
            // 这里是对链接进行处理
            line = line.replaceAll("</?a[^>]*>", "");
            // 这里是对样式进行处理
            line = line.replaceAll("<(\\w+)[^>]*>", "<$1>");
            sb.append(line);
        }

        is.close();
        br.close();

        String str = sb.toString().trim().replaceAll(" ", "");
        // 将字符串按照 ' , ' 分割
        String[] arrData = str.split(",");

        // 删除掉 【】 “ 和 data:
        String[] removeLetter = {"\\{|}", "\"", "data:"};
        for (int i = 0; i < arrData.length; i++) {
            for (String s : removeLetter) {
                arrData[i] = arrData[i].replaceAll(s, "");
            }
        }

        int temp = 0;
        HashMap<String, String> map = new HashMap<>();
        B:for (int i = 0; i < arrData.length; i++) {
            // 因为下面需要以 ” : “ 为分隔符， 防止 http: 被分割失效 (方法很屎，以后改)
            if (arrData[i].contains("http")) {
                arrData[i] = arrData[i].replaceFirst(":", "-");
                arrData[i] = arrData[i].replaceFirst(":", "-");
                arrData[i] = arrData[i].replaceFirst("-", ":");
            }

            // 以 “ : ” 分割
            String[] datas = arrData[i].split(":", 3);
            datas[1] = datas[1].replaceAll("-", ":");
            for (int j = 0; j < GET_DATA.length; j++) {
                if (datas[0].equals(GET_DATA[j])) {
                    temp++;
                    // 将数据以 【数据名， 数量】 添加进map
                    map.put(datas[0].trim(), datas[1].trim());
                }
                // 检测掉 GET_DATA 数组中所有数据添加完毕，结束这个循环
                if (temp == GET_DATA.length) {
                    break B;
                }
            }
        }


        return map;
    }


}

